package com.zhao.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhao.eduservice.entity.EduSubject;
import com.zhao.eduservice.entity.excel.SubjectData;
import com.zhao.eduservice.service.EduSubjectService;
import com.zhao.servicebase.exceptionhandler.GuliException;

import java.util.Map;

/**
 * @author xiaoZhao
 * @date 2022/10/14
 * @describe
 */
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    public EduSubjectService eduSubjectService;

    public SubjectExcelListener() {
    }

    public SubjectExcelListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }

    @Override
    public void invoke(SubjectData data, AnalysisContext context) {
        if (data == null){
            throw new GuliException(20001,"文件数据为空");
        }
        //判断一级分类是否重复
        EduSubject existOneSubject = this.existOneSubject(data.getOneSubjectName(),eduSubjectService);
        if(existOneSubject == null) { //没有相同一级分类，进行添加
            existOneSubject = new EduSubject();
            existOneSubject.setParentId("0");
            existOneSubject.setTitle(data.getOneSubjectName());//一级分类名称
            eduSubjectService.save(existOneSubject);
        }

        //获取一级分类id值
        String pid = existOneSubject.getId();
        //添加二级分类
        //判断二级分类是否重复
        EduSubject existTwoSubject = this.existTwoSubject(data.getTwoSubjectName(),eduSubjectService, pid);
        if(existTwoSubject == null) {
            existTwoSubject = new EduSubject();
            existTwoSubject.setParentId(pid);
            existTwoSubject.setTitle(data.getTwoSubjectName());//二级分类名称
            eduSubjectService.save(existTwoSubject);
        }

    }
    // 判断一级分类不能重复添加
    private EduSubject existOneSubject(String name,EduSubjectService eduSubjectService){
        QueryWrapper<EduSubject> wrapper =new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        EduSubject subject = eduSubjectService.getOne(wrapper);
        return subject;
    }

    // 判断二级分类不能重复添加
    private EduSubject existTwoSubject(String name,EduSubjectService eduSubjectService,String pid){
        QueryWrapper<EduSubject> wrapper =new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        EduSubject subject = eduSubjectService.getOne(wrapper);
        return subject;
    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }
}
